package cn.wyj.system.service.impl;

import cn.wyj.system.domain.Menu;
import cn.wyj.system.mapper.MenuMapper;
import cn.wyj.system.service.IMenuService;
import cn.wyj.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author itsource
 * @since 2022-10-24
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> tree() {
        List<Menu> result = new ArrayList<>();
        List<Menu> menus = super.findAll();
        Map<Long, Menu> menusMap = menus.stream().collect(Collectors.toMap(Menu::getId, e -> e));

        menus.forEach(menu -> {
            if (null == menu.getParentId()){
                result.add(menu);
            }else {
                Menu parent = menusMap.get(menu.getParentId());
                if (null == parent){
                    return;
                }
                parent.getChildren().add(menu);
            }
        });

        return result;
    }

    @Override
    public List<Menu> first() {
        List<Menu> all = super.findAll();
        return all.stream().filter(al->null == al.getParentId()).collect(Collectors.toList());

    }
}
